import React from 'react';
import { PlusOutlined } from '@ant-design/icons';

import {
  Form,
  Input,
  InputNumber,
  Cascader,
  Select,
  Table,
  Upload, 
  Modal,
  Row,
  Col,
  Checkbox,
  Button,
  AutoComplete,
} from 'antd';

import {getProductAttributeCategoryList} from '@/api/pms/productAttributeCategoryApi.js';
import {getProductAttributeList} from '@/api/pms/productAttributeApi.js'
const { Option } = Select;
const {Group} = Checkbox;

//读取图片资源，转换成一个路径
function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
  });
}



export default  class extends React.Component{
	state={
		flistUrl:"",
		productCategoryOptions:[],
		productAttributeStandardList:[],
		productAttributeParamList:[],
		opt0:[],
		inputValue:null,
		standardValues:{},
		columnData:[],
		oldColumnData:[
			{
				title: '销售价格',
				dataIndex: 'sale',
				render:()=><Input />
			},
			{
				title: '商品库存',
				dataIndex: 'stock',
				render:()=><Input />
			},
			{
				title: '库存预警值',
				dataIndex: 'low_stock',
				render:()=><Input />
			},
			{
				title: 'SKU编号',
				dataIndex: 'skuId',
				render:()=><Input />
			},
			{
				title: '操作',
				render:()=>{
					return <Button size="small">删除</Button>
				}
			},
		],
		dataSource:[
			// {颜色:"红色",尺寸:"M",sale:"99",stock:"88",'low_stock':"2",skuId:"33"},
			// {颜色:"红色",尺寸:"M",sale:"99",stock:"88",'low_stock':"2",skuId:"33"},
			// {颜色:"红色",尺寸:"M",sale:"99",stock:"88",'low_stock':"2",skuId:"33"},
			// {颜色:"红色",尺寸:"M",sale:"99",stock:"88",'low_stock':"2",skuId:"33"}
		],
		 previewVisible: false,   //不显示
		    previewImage: '',   
		    previewTitle: '',
		    fileList: [
		      // {
		      //   uid: '-1',
		      //   name: 'image.png',
		      //   status: 'done',
		      //   url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
		      // }
		    ]
	}
	componentDidMount(){
		getProductAttributeCategoryList({pageSize:999}).then(data=>{
				 data.data.list.forEach(item=>{
					 item.value = item.id;
					 item.label = item.name;
				 })
				 this.setState({
					productCategoryOptions:data.data.list
				 })
		})
	}
	
	handleTypeChange=(tid)=>{
		this.setState({
			opt0:[],
			inputValue:'',
			standardValues:{}
		})
		
		//根据分类id，查询属性列表和参数列表
		let param = {
			pageSize:999,
			pageNum:1,
			type:0
		}
		getProductAttributeList(param,tid[0])
		.then(data=>{
			console.log("属性列表-->",data);
			//根据data中的handAddStatus的0表示选择，1表示手动录入
			/*
				[
					{title:xx,dataIndex:xx},{title:xx,dataIndex:xx},
				]
			*/
		   let arrTmp = [];
		   data.data.list.forEach(item=>{
			   arrTmp.push({
				   title:item.name,
				   dataIndex:item.name
			   })
		   })
		   
			this.setState({
				productAttributeStandardList:data.data.list,
				columnData:[].concat(...arrTmp,...this.state.oldColumnData)
			})
			
			
		})
		
		
		param.type=1;
		getProductAttributeList(param,tid[0])
		.then(data=>{
			console.log("参数列表-->",data);
			this.setState({
				productAttributeParamList:data.data.list
			})
		})
	}
	
	handleAddStandardValue=()=>{
		let opt0 = this.state.opt0;
		opt0.push({
			label:this.state.inputValue,
			value:this.state.inputValue
		})
		console.log("---<",opt0)
		
		this.setState({
			opt0:JSON.parse(JSON.stringify(opt0)),
			inputValue:''
		})
		
		
		
		//  this.state.opt0    @1234
		//  opt0.push({})      改变了@1234这个地址里面的值，地址本身没改
		//  opt0:opt0          在react检测的时候，并没有发生任何变化
	}
	
	changeInput=(value)=>{
		let v = value.currentTarget.value;
		this.setState({
			inputValue:v
		})
	}
	
	handleDeleteStandard=(index)=>{
		console.log(index);//从opt0里面删除
		
		
		let opt0 = this.state.opt0;
		opt0.splice(index,1);
		
		this.setState({
			opt0:JSON.parse(JSON.stringify(opt0)),
		})
		
		
	}
	
	handleChangeStandardCheck=(value,name)=>{
		//怎么收集3个值
		console.log(value,name)
		
		let standardValues = Object.assign({},this.state.standardValues,{
			[name]:value
		})
		
		this.setState({
			standardValues:standardValues
		})
		
		console.log(">>>>",standardValues)
		
	}
	
	flushList=()=>{
		
		let obj = this.state.standardValues;
		
		let keys = Object.keys(obj);
		
		let ar0 = [];
		
		keys.forEach(item=>{   //颜色，尺码，风格
			if(ar0.length==0){
				obj[item].forEach(item2=>{
					ar0.push({[item]:item2});
				})
			}else{
				let tmp = [];
				obj[item].forEach(item2=>{  //红色，黄色，m，l
					//先把原有的值，复制一份，然后放到一个新的数组里面
					let oldAr = JSON.parse(JSON.stringify(ar0));
					oldAr.forEach(item3=>{   //{颜色：红色},{颜色：黄色}
						item3[item] = item2;
					})
					tmp = tmp.concat(...oldAr);
				})
				ar0 = JSON.parse(JSON.stringify(tmp));;
			}
		})
		//{sale:"0",stock:"0",'low_stock':"0",skuId:"0"}
		let oo = {sale:"0",stock:"0",'low_stock':"0",skuId:"0"};
		ar0.forEach(item=>{
			Object.assign(item,oo);
		})
		this.setState({
			dataSource:ar0
		})
	}
	
	
	 handleCancel = () => this.setState({ previewVisible: false });
	
	handlePreview = async file => {
		if (!file.url && !file.preview) {
			file.preview = await getBase64(file.originFileObj);
		}

		this.setState({
			previewImage: file.url || file.preview,
			previewVisible: true,
			previewTitle: file.name || file.url.substring(file.url.lastIndexOf('/') + 1),
		});
	};

    handleChange = ({ file,fileList }) => {
		this.setState({ fileList });
		
		if(file.status == "done"){
			let flistUrl = [],baseUrl = "http://8.129.190.90:10082";
			fileList && fileList.forEach(item=>{
				flistUrl.push(baseUrl+item.response.msg);
			})
			
			console.log("上传的图片地址："+flistUrl)
			this.setState({
				flistUrl:flistUrl
			})
		}
	}

	render(){
		
	 const { previewVisible, previewImage, fileList, previewTitle } = this.state;
		const uploadButton = (
		  <div>
			<PlusOutlined />
			<div style={{ marginTop: 8 }}>Upload</div>
		  </div>
		);
			
			
	  const onFinish = (values) => {
		  
		  
		  //处理商品属性分类id
		  values.productAttributeCategoryId = values.productAttributeCategoryId[0];
		  
		  
		  values.pic = this.state.flistUrl.join(",");
		  
		  console.log('第三个页面: ', values);
		  
		  Object.assign(productData,values);
		  
		  handleStep(1);
		};
		
		//写循环，哈哈哈
		let standard = this.state.productAttributeStandardList.map(item=>{
			if(item.handAddStatus){  //不为0  手动录入
			return <>
				<br/><br/>
				{item.name}
				<br/><br/>
				<Group
					onChange={(value)=>{this.handleChangeStandardCheck(value,item.name)}}
				>
					{this.state.opt0.map((item,index)=>{
						return <>
							<Checkbox value={item.value}>{item.label}</Checkbox>
							<a href="javascript:void(0)" onClick={this.handleDeleteStandard.bind(this,index)}>删除</a>&nbsp;&nbsp;&nbsp;&nbsp;
						</>
					})}
				</Group>
				<br/>
				<input value={this.state.inputValue} onChange={this.changeInput} /><Button size="small" onClick={this.handleAddStandardValue}>添加</Button>
			</>
				
			}else{  //为0，选择
			let arr = item.inputList.split(",");
			let opt1 = [];
			arr.forEach(it=>{
				opt1.push({label:it,value:it})
			})
				return <>
					<br/><br/>
					{item.name}
					<br/><br/>
					<Group
						options={opt1}
					onChange={(value)=>{this.handleChangeStandardCheck(value,item.name)}}
					></Group>
				</>
			}
		})
		
		//循环出参数列表(productAttributeParamList)
		let paramEle = this.state.productAttributeParamList.forEach(item=>{
			//
		})
		
		
		const {handleStep,productData} = this.props;
		
		
	  return <Form
		name="proinfo"
		onFinish={onFinish}
		style={{marginTop:'20px'}}
	  >
		<Form.Item
			style={{marginLeft:'20px',textAlign:'left',width:'300px'}}
			name="productAttributeCategoryId"
			label="属性类型"
		>
		  <Cascader onChange={this.handleTypeChange} options={this.state.productCategoryOptions} placeholder='请选择'/>
		</Form.Item>
		<Form.Item
			style={{marginLeft:'20px',textAlign:'left'}}
			name="category123"
			label="商品规格"
		>
		  <div style={{padding:"30px 20px",border:"2px solid #ccc",width:"100%",backgroundColor:"#f8f9fc",minHeight:"50px"}}>
			{standard}
		  </div>
		  <Table
			columns ={this.state.columnData}
			pagination={false}
			bordered
			dataSource={this.state.dataSource}
		  >
		  </Table>
		  <Button type="primay" onClick={this.flushList}>刷新列表</Button>
		</Form.Item>
		<Form.Item
			style={{marginLeft:'20px',textAlign:'left'}}
			name="productParam"
			label="商品参数"
		>
		  <div style={{background:"#f8f9fc",padding:"30px 20px",border:"2px solid #ccc",width:"100%",minHeight:"50px"}}>
			{standard}
		  </div>
		  
		</Form.Item>
		<Form.Item
			style={{marginLeft:'20px',textAlign:'left'}}
			name="pic"
			label="商品相册"
		>
			<Upload
			  action="http://8.129.190.90:10082/fileUpload"
			  listType="picture-card"
			  fileList={fileList}
			  onPreview={this.handlePreview}
			  onChange={this.handleChange}
			>
			  {fileList.length >= 6 ? null : uploadButton}
			</Upload>
			<Modal
			  visible={previewVisible}
			  title={previewTitle}
			  footer={null}
			  onCancel={this.handleCancel}
			>
			  <img alt="example" style={{ width: '100%' }} src={previewImage} />
			</Modal>
		</Form.Item>
	  <Button type="primary" onClick={handleStep.bind(this,-1)}>上一步,填写商品促销</Button>
	  <Button type="primary" htmlType="submit">下一步,填写商品关联</Button>
	  </Form>
  }
} 